package com.dcjt.firehotcarpad.utils

import NewMessagePool
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.allen.library.SuperTextView
import com.aries.library.fast.manager.LoggerManager
import com.aries.library.fast.retrofit.FastObserver
import com.aries.library.fast.util.FastStackUtil
import com.aries.library.fast.util.SizeUtil
import com.aries.library.fast.util.ToastUtil
import com.aries.ui.view.radius.RadiusTextView
import com.aries.ui.widget.alert.UIAlertView
import com.aries.ui.widget.progress.UIProgressView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.dcjt.firehotcarpad.R
import com.dcjt.firehotcarpad.adapter.TagAdapter
import com.dcjt.firehotcarpad.entity.CombatTeamEntity
import com.dcjt.firehotcarpad.entity.SxhLx
import com.dcjt.firehotcarpad.entity.Template
import com.dcjt.firehotcarpad.manager.DataManager
import com.dcjt.firehotcarpad.model.SendMessageUtils
import com.dcjt.firehotcarpad.retrofit1.repository.ApiRepository1
import com.dcjt.firehotcarpad.widget.audiorecoder.widget.AudioRecordButton
import com.dcjt.firehotcarpad.widget.taglayout.FlowTagLayout
import com.google.gson.Gson
import com.marno.easystatelibrary.EasyStatusView
import com.trello.rxlifecycle2.android.ActivityEvent
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity
import com.yhao.floatwindow.FloatWindow
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.dialog_countdown_layout.view.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.io.File
import java.util.concurrent.TimeUnit

/**
 * Created by cj on 2021/2/23.
 * Email:codesexy@163.com
 * Function:
 * desc:
 */
object AlertDialogUtil {
    var alert :UIAlertView? = null

    /**
     * 开启倒计时弹窗
     * @param title 标题
     * @param content 内容
     * @param confirmText 确认按钮文字
     * @param callback 确认按钮事件回调
     * @param countDown 倒计时时间 默认为10秒
     */

    @SuppressLint("SetTextI18n")
    fun showCountDownDialog(
        context: Context,
        title: String,
        content: String,
        confirmText: String,
        callback: (() -> Unit),
        countDown: Int = 10
    ): AlertDialog {
        val view =
            LayoutInflater.from(context).inflate(R.layout.dialog_countdown_layout, null, false)
        val dialog = AlertDialog.Builder(context).setCancelable(false).setView(view).create()
        view.dialog_title.text = title
        view.dialog_content.text = content
        view.dialog_confirm.text = "${confirmText}($countDown)"
        val d = getTimer {
            LoggerManager.e("倒计时时间 $it")
            if (it == countDown) {
                view.dialog_confirm.performClick()
            }
            view.dialog_confirm.text = "${confirmText}(${countDown - it})"
        }
        view.dialog_cancel.setOnClickListener {
            d.dispose()
            dialog.dismiss()
        }
        view.dialog_confirm.setOnClickListener {
            d.dispose()
            dialog.dismiss()
            callback()
        }
        dialog.show()
        //此处设置位置窗体大小，我这里设置为了手机屏幕宽度的3/4  注意一定要在show方法调用后再写设置窗口大小的代码，否则不起效果会

        dialog.window?.setLayout(
            (SizeUtil.getScreenWidth() / 2),
            RelativeLayout.LayoutParams.WRAP_CONTENT
        )
        return dialog
    }

    private fun getTimer(callback: (Int) -> Unit): Disposable {
        var count = 0
        return Observable.interval(1000, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                count++
                callback(count)
            }
    }


    /**
     * 进行二次提醒
     */
    fun alertTips(
        context: Context,
        title: String,
        tips: String,
        negativeCallBack: () -> Unit = {},
        positiveCallBack: () -> Unit,
        negativeBtn: String = "取消",
        positiveBtn: String = "确定"
    ) {
        UIAlertView(context).setTitle(title).setMessage(tips)
            .setNegativeButton(negativeBtn) { dialog, _ ->
                dialog.dismiss()
                negativeCallBack()
            }
            .setPositiveButton(positiveBtn) { dialog, _ ->
                dialog.dismiss()
                positiveCallBack()
            }
            .show()
    }

    /**
     * 修改作战班
     */
    fun choiceCombatTeam(context: RxAppCompatActivity, ensure: () -> Unit, cancel: () -> Unit) {

        var contentView =
            LayoutInflater.from(context).inflate(R.layout.layout_choice_combat, null, false)
        var recyclerView: RecyclerView
        var statusView: EasyStatusView
        var title: SuperTextView
        var buttonContainer: LinearLayout
        var ensure: RadiusTextView
        var cancel: RadiusTextView
        var mAdapter: BaseQuickAdapter<CombatTeamEntity, BaseViewHolder>
        with(contentView) {
            recyclerView = findViewById(R.id.recyclerView)
            statusView = findViewById(R.id.statusView)
            title = findViewById(R.id.title)
            buttonContainer = findViewById(R.id.btnContainer)
            ensure = findViewById(R.id.btEnsure)
            cancel = findViewById(R.id.btCancel)
        }
        with(recyclerView) {
            layoutManager = GridLayoutManager(context, 2)
            adapter = object :
                BaseQuickAdapter<CombatTeamEntity, BaseViewHolder>(R.layout.item_choice_combat) {
                override fun convert(helper: BaseViewHolder?, item: CombatTeamEntity?) {
                    helper!!
                    item!!
                    with(helper.getView<RadioButton>(R.id.radioBtn)) {
                        isChecked = item.isChoice
                        text = "${item.mc}(呼号${item.hh})"
                    }
                }
            }.apply {
                mAdapter = this
            }

        }

        val alertDialog: android.app.AlertDialog = android.app.AlertDialog.Builder(context)
            .setView(contentView)
            .setCancelable(false)
            .create()
        alertDialog.show()

        statusView.loading()

        cancel.setOnClickListener {
            alertDialog.dismiss()
            cancel()
        }

        ensure.setOnClickListener {
            alertDialog.dismiss()
            ensure()
        }

        title.setCenterString(DataManager.getInstance().user.dept_name)
        buttonContainer.visibility = View.GONE

        ApiRepository1.getInstance().combatTeams
            .compose(context.bindUntilEvent(ActivityEvent.DESTROY))
            .subscribe(object : FastObserver<List<CombatTeamEntity>>() {
                override fun _onNext(entity: List<CombatTeamEntity>) {
                    statusView.content()
                    if (entity.isNotEmpty()) {
                        mAdapter.addData(entity)
                        buttonContainer.visibility = View.VISIBLE
                    } else {
                        statusView.empty()
                        title.setRightIcon(R.drawable.icon_close)
                    }
                }

                override fun _onError(errorRes: Int, errorCode: Int, e: Throwable) {
                    super._onError(errorRes, errorCode, e)
                    statusView.error()
                    title.setRightIcon(R.drawable.icon_close)
                }
            })
    }

    /**
     * 反馈的弹框
     */
    fun addDisasterDocument(activity: RxAppCompatActivity, id: String, templates: List<Template>?) {
        FloatWindow.get().hide()
        val feedBackView =
            LayoutInflater.from(activity).inflate(R.layout.layout_add_fire_document, null, false)
        alert = UIAlertView(activity).setView(feedBackView).setCancelable(false).show()
        val tagFlowLayout = feedBackView.findViewById<FlowTagLayout>(R.id.flowLayout)
        val editTextView = feedBackView.findViewById<EditText>(R.id.feedEditText)
        val rgChooseCar1 = feedBackView.findViewById<RadioGroup>(R.id.rgChooseCar1)
        val layout_ksfk = feedBackView.findViewById<LinearLayout>(R.id.layout_ksfk)
        val layout_edit = feedBackView.findViewById<LinearLayout>(R.id.layout_edit)
        val rtvSubmit = feedBackView.findViewById<RadiusTextView>(R.id.rtvSubmit)

        val layout_voice = feedBackView.findViewById<LinearLayout>(R.id.layout_voice)

        rgChooseCar1.setOnCheckedChangeListener { _, checkedId ->
            when(checkedId){
                R.id.bt0 ->{
                    layout_ksfk.visibility = View.VISIBLE
                    layout_edit.visibility = View.VISIBLE
                    rtvSubmit.visibility = View.VISIBLE
                    layout_voice.visibility = View.GONE
                }
                R.id.bt1 ->{
                    layout_ksfk.visibility = View.GONE
                    layout_edit.visibility = View.GONE
                    rtvSubmit.visibility = View.GONE
                    layout_voice.visibility = View.VISIBLE
                }
            }
        }

        if (templates != null) {
            var mAdapter = TagAdapter<Template>(activity)
            tagFlowLayout.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_SINGLE);
            tagFlowLayout.adapter = mAdapter
            mAdapter.onlyAddAll(templates)
            tagFlowLayout.setOnTagSelectListener { _, selectedList ->
                selectedList.forEachIndexed { index, i ->
                    editTextView.setText(templates[i].mb)
                }
            }
            tagFlowLayout.clearAllOption()
        } else {

        }
        feedBackView.findViewById<SuperTextView>(R.id.title).rightIconIV.setOnClickListener {
            alert?.dismiss()
        }
        alert?.setOnDismissListener {
            FloatWindow.get().show()
        }
        var recordButton = feedBackView.findViewById<AudioRecordButton>(R.id.audioRecord)
        recordButton.setAudioFinishRecorderListener { _, filePath ->
            FileUtils.upLoadFile(activity, File(filePath), object : FileUtils.LoadFileListener {
                override fun onSuccess(url: List<String>?) {
                    var list: MutableList<SxhLx> = mutableListOf()
                    url?.forEach {
                        list.add(SxhLx("audio", it))
                    }
                    saveDocument(activity, id, "", list)


                }

                override fun onError(errMsg: String?) {
                    ToastUtil.show(errMsg)
                }
            })
        }
//        val ivVoice = feedBackView.findViewById<ImageView>(R.id.ivVoice)
        feedBackView.findViewById<RadiusTextView>(R.id.rtvSubmit).setOnClickListener {
            val content = editTextView.text.toString()
            if (TextUtils.isEmpty(content)) {
                ToastUtil.show("您未输入任何内容，请输入内容后提交")
            } else {
                saveDocument(activity, id, content, null)
            }
        }
    }


    fun saveDocument(
        activity: RxAppCompatActivity,
        id: String,
        content: String,
        data: List<SxhLx>?
    ) {
        val map = HashMap<String, Any>()
        map["ly"] = "app"
        map["zqid"] = id
        map["czlx"] = "33"

        map["content"] = hashMapOf(
            Pair("lx", "快速反馈"),
            Pair("text", content),
            Pair("links", data ?: intArrayOf())
        )
        val progressView = UIProgressView(activity).setMessage("发送中...")
        progressView.show()
        progressView.setCancelable(false)

        ApiRepository1.getInstance()
            .saveDocument(createBody(hashMapOf(Pair("data", Gson().toJson(map)))))
            .compose(activity.bindUntilEvent(ActivityEvent.DESTROY))
            .subscribe(object : FastObserver<Any>() {
                override fun _onNext(entity: Any) {
                    LoggerManager.e(entity.toString())
                    ToastUtil.show("添加成功")
                    progressView.dismiss()
                    NewMessagePool.get().onReceiveDocumentMsg()
                    //发送消息  通知其他端
                    SendMessageUtils.get()
                        .sendMessage(
                            DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.buZ_SXH_SAVE,
                            id, activity, null
                        )
                    if (alert != null){
                        alert?.dismiss()
                    }

                }

                override fun _onError(errorRes: Int, errorCode: Int, e: Throwable) {
                    super._onError(errorRes, errorCode, e)
                    LoggerManager.e(e.message)
                    ToastUtil.show("添加失败")
                    progressView.dismiss()
                }

            })
    }

    fun createBody(data: Any): RequestBody {
        return RequestBody.create(
            "application/json".toMediaTypeOrNull(),
            Gson().toJson(data)
        )
    }
    /**
     * 拨打电话
     */
    fun showTipAlert(phone: String) {
        alertTips(FastStackUtil.getInstance().current,
            FastStackUtil.getInstance().current.resources.getString(R.string.tips), "立即拨打电话   ${phone} ？",
            {
            }, {
                //拨打电话
                var intent : Intent =  Intent(Intent.ACTION_DIAL)
                var data : Uri = Uri.parse("tel:${phone}" );
                intent.setData(data);
                FastStackUtil.getInstance().current.startActivity(intent);
            }, negativeBtn = "取消", positiveBtn = "确定"
        )
    }
}

